<template>
  <div class="app-container">
    <!--工具栏-->
    <crudOperation :permission="permission" >
      <el-button :disabled="crud.selections.length !== 1" class="filter-item" size="mini" type="success" @click="edit"  slot="left">修改</el-button>
    </crudOperation>
    <div class="head-container">

      <!--表单组件-->
      <el-dialog  :visible.sync="showDialog" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="基本工资">
            <el-input v-model="form.salary" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="客户家数">
            <el-input disabled v-model="form.customerCount" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="家数提成">
            <el-input @change="customerCountPerformance" v-model="form.customerCountCommission" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="家数绩效">
            <el-input disabled v-model="form.customerCountPerformance" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="绩效类型">
            <el-select
              v-model="performanceType"
              placeholder="类型"
              size="small"
              style="width: 100%"
              @change="changePerformanceType"
            >
              <el-option
                :key="1"
                label="件数"
                :value="1"
              />
              <el-option
                :key="2"
                label="千克数"
                :value="2"
              />
              <el-option
                :key="3"
                label="立方数"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <div v-if="performanceType === 1">
            <el-form-item label="件数目标" >
              <el-input v-model="form.goodsCountGoal" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="件数">
              <el-input disabled v-model="form.goodsCount" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="件数提成">
              <el-input @change="computedGoodsCountPerformance" v-model="form.goodsCountCommission" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="件数绩效">
              <el-input disabled v-model="form.goodsCountPerformance" style="width: 370px;" />
            </el-form-item>
          </div>
          <div v-if="performanceType === 2">
            <el-form-item label="千克数目标">
              <el-input v-model="form.weightGoal" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="千克数">
              <el-input disabled v-model="form.weight" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="千克数提成">
              <el-input @change="computedWeightPerformance" v-model="form.weightCommission" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="千克数绩效">
              <el-input disabled v-model="form.weightPerformance" style="width: 370px;" />
            </el-form-item>
          </div>
          <div v-if="performanceType === 3">
            <el-form-item label="立方数目标">
              <el-input v-model="form.volumeGoal" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="立方数">
              <el-input disabled v-model="form.volume" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="立方数提成">
              <el-input @change="computedVolumePerformance" v-model="form.volumeCommission" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="立方数绩效">
              <el-input disabled v-model="form.volumePerformance" style="width: 370px;" />
            </el-form-item>
          </div>
          <el-form-item label="趟数目标">
            <el-input disabled v-model="form.orderCountGoal" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="趟数">
            <el-input disabled v-model="form.orderCount" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="趟数提成">
            <el-input @change="computedOrderCountPerformance" v-model="form.orderCountCommission" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="趟数绩效">
            <el-input disabled v-model="form.orderCountPerformance" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-dialog>
      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>
      <div>选择年月</div>
      <div class="flex">
        <el-date-picker
          v-model="month"
          type="month" @change="getYear"
          :clearable="false"
          placeholder="选择年" style="width:30%"/>
        <rrOperation :crud="crud"/>
      </div>
      <!--表格渲染-->
      <el-table ref="table" border :data="crud.data" size="small"
                style="width: 100%;" v-if="isShowTable"
                show-summary
                height="700"
                :summary-method="crud.sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @contextmenu.native="showMenu"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <el-table-column prop="userName" label="人员名称" />
        <el-table-column prop="salary" label="基本工资" />
        <el-table-column prop="customerCount" label="家数" />
        <el-table-column prop="customerCountGoal" label="家数目标" />
        <el-table-column prop="customerCountCommission" label="家数提成" />
        <el-table-column prop="customerCountCompletionRate" label="家数完成率" />
        <el-table-column prop="customerCountPerformance" label="家数绩效" />
        <el-table-column prop="goodsCountGoal" label="件数目标" />
        <el-table-column prop="goodsCountCommission" label="件数提成" />
        <el-table-column prop="goodsCount" label="件数" />
        <el-table-column prop="goodsCountCompletionRate" label="件数完成率" />
        <el-table-column prop="goodsCountPerformance" label="件数绩效" />
        <el-table-column prop="orderCountGoal" label="趟数目标" />
        <el-table-column prop="orderCountCommission" label="趟数提成" />
        <el-table-column prop="orderCount" label="趟数" />
        <el-table-column prop="orderCountCompletionRate" label="趟数完成率" />
        <el-table-column prop="orderCountPerformance" label="趟数绩效" />
        <el-table-column prop="weightGoal" label="千克数目标" />
        <el-table-column prop="weightCommission" label="千克数提成" />
        <el-table-column prop="weight" label="千克数" />
        <el-table-column prop="weightPerformance" label="千克数绩效" />
        <el-table-column prop="weightCompletionRate" label="千克数完成率" />
        <el-table-column prop="volumeGoal" label="立方数目标" />
        <el-table-column prop="volumeCommission" label="立方数提成" />
        <el-table-column prop="volumeCompletionRate" label="立方数完成率" />
        <el-table-column prop="volume" label="立方数" />
        <el-table-column prop="volumePerformance" label="立方数绩效" />
        <el-table-column prop="totalSalary" label="总工资" />
      </el-table>
      <!--分页组件-->

      <pagination/>
    </div>
  </div>
</template>

<script>
import crudReportDriverLoad, {reportDriverAssessmentAdd} from '@/api/erp/driverExamineReport'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {getBasGoodsTypeTree} from "@/api/erp/basGoodsType";
import Treeselect from '@riophae/vue-treeselect'
import {get} from '@/api/erp/reportDriverLoad'
import { publicListKey } from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";
import {getAreaTree} from "@/api/erp/basCustomerArea";
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import tableSelect from '@/components/tableSelect/tableSelect'
//获取当前年月
const date = new Date()
const curYear = date.getFullYear()
const curMonth = date.getMonth() + 1

// crud交由presenter持有
const defaultCrud = CRUD({ title: '司机考核报表',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false
  },
  query:{
  year:curYear,
    month:curMonth
  },
  url: 'api/reportDriverAssessment', sort: '',
  crudMethod: { ...crudReportDriverLoad }})
const defaultForm = { busDate: null, orderType: null, orderId: null, orderCode: null, orderName: null, orderStatus: null, customerId: null, customerCode: null, customerName: null, pCustomerId: null, pCustomerCode: null, pCustomerName: null, mCustomerId: null, mCustomerCode: null, mCustomerName: null, deptId: null, deptCode: null, deptName: null, userId: null, userCode: null, userName: null, warehouseId: null, warehouseCode: null, warehouseName: null, orderRemark: null, goodsId: null, goodsCode: null, goodsName: null, packageType: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, boxUnitId: null, boxUnitCode: null, boxUnitName: null, boxUnitCount: null, boxNum: null, mainUnitId: null, mainUnitCode: null, mainUnitName: null, mainUnitCount: null, mainNum: null, goodsCount: null, boxCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, taxAmount: null, noTaxAmount: null, tax: null, acceptGoodsCount: null, acceptBoxCount: null, acceptBoxNum: null, acceptMainNum: null, acceptTaxAmount: null, acceptNoTaxAmount: null, acceptTax: null, cancelAmount: null, unCancelAmount: null, goodsRemark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, auditUserId: null, auditUserCode: null, auditUserName: null, auditTime: null, closeUserId: null, closeUserCode: null, closeUserName: null, closeTime: null, acceptDate: null, acceptUserId: null, acceptUserCode: null, acceptUserName: null, cancelDate: null, cancelUserId: null, cancelUserCode: null, cancelUserName: null, id: null }
export default {
  name: 'ReportDriverLoad',
  components: { pagination, crudOperation, rrOperation, udOperation,Treeselect,jTableColumnConfig, tableSelect },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts:['t_report_Driver_flow_order_type','common_order_status','common_cancel_status','common_yes_or_no','t_bas_goods_package_type'],

  mounted(){
    const date  = new Date().toISOString().split('T')[0]
    this.dataExtent[0] = date
    this.dataExtent[1] = date
    this.crud.props.searchToggle =false
  },
  created() {
    this.month = `${curYear}-${curMonth}`
    console.log(this.month)
    getCustomerTypeTree({size:999}).then(res=>{
      this.customerTypeList = res
    })
    this.getAreaTree()
  },
  data() {
    return {
      customerTypeIds:[],
      isSend:[],
      fCustomerIds:[],
      pCustomerIds:[],
      mCustomerIds:[],
      customerAreaIds:[],
      total:0,
      areaList:[],
      orderType:[],
      cancelStatus:[],
      orderStatus:[],
      createdataExtent:[],
      dialogVisible:false,
      dataExtent:[],
      dataExtent01:[],
      dataExtent02:[],
      goodsTypeIds:[],
      goodsBrandIds:[],
      warehouseIds:[],
      goodsIds:[],
      performanceType:1,
      driverUserIds:[],
      areaData:[],
      customerIds:[],
      sCustomerIds:[],
      packageType:[],
      showDialog:false,
      form:{},
      month:"",
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      jumpPath:[
        '/sale/salesorderDetail/',
        '/sale/salesorderDetail/',
        '/ware/wareReturnBottleBoxDetail/',
      ],
      goodsTagList:[],
      userIds:[],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      permission: {
        add: ['admin', 'reportDriverLoad:add'],
        edit: ['admin', 'reportDriverLoad:edit'],
        del: ['admin', 'reportDriverLoad:del'],
        import: ['admin', 'reportDriverLoad:import'],
        export: ['admin', 'reportDriverLoad:export'],
        copy: ['admin', 'reportDriverLoad:copy'],
        upload: ['admin', 'reportDriverLoad:upload'],
        download: ['admin', 'reportDriverLoad:download'],
        pass: ['admin', 'reportDriverLoad:pass'],
        reject: ['admin', 'reportDriverLoad:reject'],
        closed: ['admin', 'reportDriverLoad:closed'],
        invalid: ['admin', 'reportDriverLoad:invalid'],
        stop: ['admin', 'reportDriverLoad:stop'],
        recover: ['admin', 'reportDriverLoad:recover'],

      },
      rules: {
        goodsId: [
          { required: true, message: '商品id不能为空', trigger: 'blur' }
        ]
      },
    }
  },

  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  watch: {
    customerTypeIds(n){
      if (!n.length){
        this.query.customerTypeIds = null
      }
    },
    packageType(n,o){
      if (n.length){
        this.query.packageType = this.packageType.join(',')
      }else{
        this.query.packageType =null
      }
    }
    // goodsTypeIds(n){
    //   if (!n.length){
    //     this.query.goodsTypeIds = null
    //   }
    // },
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.afterRefresh]() {
      this.month = `${this.query.year}-${this.query.month<10?"0"+this.query.month:this.query.month}`
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    edit(){
      this.form = this.crud.selections[0]
      this.showDialog = true
    },
    getValue(e){
      if (this.dataExtent){
        this.query.startBusDate = this.dataExtent[0]
        this.query.endBusDate = this.dataExtent[1]
      }else {
        this.query.startBusDate = null
        this.query.endBusDate = null
      }
    },
    getYear(e){
      const date = new Date(e)
      this.crud.query.year = date.getFullYear()
      this.crud.query.month = date.getMonth() + 1
      this.month = `${date.getFullYear()}-${date.getMonth()<9?"0"+(date.getMonth() + 1):date.getMonth() + 1}`
    },
    changePerformanceType(e){
      //切换绩效类型时清空其他两个类型的提成和绩效
      switch (e){
        case 1:
          this.form.weightCommission = 0
          this.form.weightPerformance = 0
          this.form.volumeCommission = 0
          this.form.volumePerformance = 0
          break
        case 2:
          this.form.goodsCountCommission = 0
          this.form.goodsCountPerformance = 0
          this.form.volumeCommission = 0
          this.form.volumePerformance = 0
          break
        case 3:
          this.form.weightPerformance = 0
          this.form.weightCommission = 0
          this.form.goodsCountCommission = 0
          this.form.goodsCountPerformance = 0
          break
      }

    },
    computedGoodsCountPerformance(){
      this.form.goodsCountPerformance = this.form.goodsCount * this.form.goodsCountCommission
    },
    computedVolumePerformance(){
      this.form.volumePerformance = this.form.volume * this.form.volumeCommission
    },
    computedWeightPerformance(){
      this.form.weightPerformance = this.form.weight * this.form.weightCommission
    },
    customerCountPerformance(){
      this.form.customerCountPerformance = this.form.customerCount * this.form.customerCountCommission
    },
    computedOrderCountPerformance(){
      this.form.orderCountPerformance = this.form.orderCount * this.form.orderCountCommission
    },
    async save(){
      const res = await reportDriverAssessmentAdd([this.form])
      if(res.status === 200){
        this.$message.success('保存成功')
        this.showDialog = false
        this.crud.refresh()
      }else{
        this.$message.error(res.msg)
      }
    },
    getAreaTree() {
      getAreaTree({status: 1}).then(res => {
        this.areaData = res
        this.areaList = res
      })
    },
    getSendValue(e){
      if (this.dataExtent01) {
        this.query.sendStartDate = this.dataExtent01[0]
        this.query.sendEndDate = this.dataExtent01[1]
      }else {
        this.query.sendStartDate = null
        this.query.sendEndDate = null
      }
    },
    getTypeChildren(val){
      console.log(val)
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    init(){
      this.page = 1
    },
    getBillCode(ids){
      if (ids){
        return ids.split(',')
      }
    },
    onGet(){
      const that =this
      let { page,size } = this.crud.page
      page =  1
      get({...this.query,page,size}).then(res=>{
        that.crud.data = res.data.content
        that.crud.page.total = res.data.totalElements
        console.log(that.total)
      })
    },
    jumpSend(ids,index,path,row){
      const idsList = ids.split(',')
      if (path === '/ware/wareSalesInvoiceDetail/'){
        const typeList = row.sendOrderType.split(',')
        switch (typeList[index]){
          case '2':
            path = '/ware/wareSalesReturnDetail/'
            break
          case '3':
            path = '/ware/wareReturnBottleBoxDetail/'
            break
        }
      }
      this.$router.push({path:`${path}${idsList[index]}`})
    },
    jump(row){
      this.$router.push({path:this.jumpPath[Number(row.orderType)-1]+row.orderId})
    },
    onCustomerNode(node){
      this.query.customerTypeIds = this.getNode(node,this.query.customerTypeIds?this.query.customerTypeIds:'')
    },
    getgoodsType(val){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this.areaList,item)
        str = this.getNode(itemNode,str)
      })
      this.query.goodsTypeIds = str
    },
    getArea(val){
      let str = ''
      console.log(this.areaList)
      val.forEach(item=>{
        const itemNode = this.getTreeName(this.areaList,item)
        str = this.getNode(itemNode,str)
      })
      this.query.customerAreaIds = str
    },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===
          id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    delgoodsType(node){
      const list = this.getNode(node,'').split(',')
      const oldList = this.query.goodsTypeIds.split(',')
      for(let i =oldList.length;i>0;i--){
        console.log(list)
        console.log(oldList[i])
        console.log(list.includes(oldList[i]))
        if (list.includes(oldList[i])){
          oldList.splice(i,1)
        }
      }
      this.query.goodsTypeIds = oldList.join(',')
      console.log(this.query.goodsTypeIds)
    },
    delareaType(node){
      const list = this.getNode(node,'').split(',')
      const oldList = this.query.customerAreaIds.split(',')
      for(let i =oldList.length;i>0;i--){
        if (list.includes(oldList[i])){
          oldList.splice(i,1)
        }
      }
      this.query.customerAreaIds = oldList.join(',')
      console.log(this.query.customerAreaIds)
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    resetQuery(){

      this.goodsTypeIds = []
      this.orderType  = []
      this.cancelStatus=[]
      this.goodsBrandIds = []
      this.orderStatus  = []
      this.warehouseIds = []
      this.pCustomerIds = []
      this.mCustomerIds = []
      this.goodsIds = []
      this.isSend = []
      this.driverUserIds = []
      this.customerAreaIds = []
      this.userIds=[]
      this.dataExtent = []
      this.packageType = []
      this.dataExtent01 = []
      this.driverUserids =[]
      this.goodsTagList = []
      this.fCustomerIds = []
      this.customerIds = []
      this.customerTypeIds=[]
      this.dataExtent02=[]
      this.sCustomerIds=[]
      this.createdataExtent = []
      this.crud.resetQuery()
    },
    checkArea(data, node) {
      this.query.customerAreaId = data.id
      // this.$refs.areaTree.setCheckedNodes([node])
      this.crud.toQuery()
    },
    queryReport(){
      this.init()
      this.crud.toQuery()
      this.crud.props.searchToggle = false
    }
  }
}
</script>

<style lang="scss" scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.flex{
  display: flex;
}
.fow-reverse{
  flex-direction: row-reverse;
}
.codeJump{
  background-image:-webkit-linear-gradient(top,yellow,#ff00fb);
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  cursor: pointer;
}
</style>
